package org.mzyyn.qr.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.mzyyn.qr.context.UserAuthContext;
import org.mzyyn.qr.dto.prize.PrizeRecordListDTO;
import org.mzyyn.qr.entity.PrizeRecordPO;
import org.mzyyn.qr.mapper.PrizeRecordMapper;
import org.mzyyn.qr.service.PrizeRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.mzyyn.qr.vo.prize.PrizeRecordListVO;
import org.qr.xiaocao.common.constants.PageInfoConstant;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 产品记录表 服务实现类
 * </p>
 *
 * @author lipeng
 * @since 2024-09-04
 */
@Service
public class PrizeRecordServiceImpl extends ServiceImpl<PrizeRecordMapper, PrizeRecordPO> implements PrizeRecordService {

    @Override
    public void insertRecord(String uuid, String prizeName, String prizeOperate, String scece,String shareCode) {
        PrizeRecordPO prizeRecordPO = new PrizeRecordPO();
        prizeRecordPO.setUserUuid(uuid);
        prizeRecordPO.setPrizeName(prizeName);
        prizeRecordPO.setPrizeVal(prizeOperate);
        prizeRecordPO.setPrizeDesc(scece);
        prizeRecordPO.setShareCode(shareCode);
        prizeRecordPO.setCreateTime(LocalDateTime.now());
        prizeRecordPO.setUpdateTime(LocalDateTime.now());
        this.baseMapper.insert(prizeRecordPO);

    }

    @Override
    public Page<PrizeRecordListVO> getRecordList(PrizeRecordListDTO prizeRecordListDTO) {
        Integer pageSize = prizeRecordListDTO.getPageSize();
        Integer pageNum = prizeRecordListDTO.getPageNum();
        if( null == pageNum ){
            pageNum = PageInfoConstant.PAGE_NUM;
        }
        if( null == pageSize ){
            pageSize = PageInfoConstant.PAGE_SIZE;;
        }

        Page<PrizeRecordListVO> res = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<PrizeRecordPO> query = new LambdaQueryWrapper<>();
        query.eq(PrizeRecordPO::getUserUuid, UserAuthContext.getUserInfo().getUuid());
        query.orderByDesc(PrizeRecordPO::getId);

        Page<PrizeRecordPO> resPage = this.baseMapper.selectPage(new Page<>(pageNum, pageSize), query);
        if( null == resPage || CollUtil.isEmpty(resPage.getRecords())){
            res.setTotal(0);
            return res;
        }

        List<PrizeRecordListVO> recordList = resPage.getRecords().stream().map(v -> {
            return BeanUtil.toBean(v, PrizeRecordListVO.class);
        }).collect(Collectors.toList());

        res.setTotal(resPage.getTotal());
        res.setRecords(recordList);

        return res;
    }
}
